/**
 * Created by PanJiaChen on 16/11/18.
 */
import Layout from '@/layout'
import { getUserInfo } from '@/utils/auth'

const constantBaseRoutes = [
  {
    path: '/redirect',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '/redirect/:path(.*)',
        component: () => import('@/views/redirect/index')
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },
  {
    path: '/auth-redirect',
    component: () => import('@/views/login/auth-redirect'),
    hidden: true
  }
]

const asyncBaseRoutes=[
  {
    path: '',
    component: Layout,
    redirect: 'dashboard',
    key: 'A',
    children: [
    ]
  },
  {
    path: '/permission',
    component: Layout,
    redirect: '/permission/index',
    alwaysShow: true,
    key: 'B',
    meta: {
      title: '权限管理',
      icon: 'lock',
      roles: ['admin', 'editor']
    },
    children: [
    ]
  },
  {
    path: '/usrgroup',
    key:'G',
    component: Layout,
    redirect: '/usrgroup/list',
    name: 'Usrgroup',
    meta: {
      title: '用户组管理',
      icon: 'el-icon-s-help'
    },
    children: [
    ]
  },
  {
    path: '/boudf',
    key:'H',
    component: Layout,
    redirect: '/boudf/list',
    name: 'BOUDF',
    meta: {
      title: 'LOT数据管理',
      icon: 'el-icon-s-marketing'
    },
    children: [
    ]
  },
  {
    path: '/usr',
    component: Layout,
    redirect: '/usr/list',
    name: 'Usr',
    key: 'C',
    meta: {
      title: '用户管理',
      icon: 'course',
      roles: ['admin', 'editor']
    },
    children: [
    ]
  },
  {
    path: '/mpcp',
    component: Layout,
    redirect: '/mpcp/list',
    name: 'MPCP',
    key: 'D',
    meta: {
      title: 'LOT执行管理',
      icon: 'el-icon-s-order'
    },
    children: [
    ]
  },

  {
    path: '/mpcpend',
    key:'I',
    component: Layout,
    redirect: '/mpcpend/list',
    name: 'MPCP',
    meta: {
      title: '生产/质量数据管理',
      icon: 'el-icon-s-help'
    },
    children: [
    ]
  },

  {
    path: '/res',
    component: Layout,
    redirect: '/res/list',
    name: 'Res',
    key: 'E',
    meta: {
      title: '设备管理',
      icon: 'course',
      roles: ['admin', 'editor']
    },
    children: [
    ]
  },

  {
    path: '/edc',
    component: Layout,
    redirect: '/edc/list',
    name: 'EDC',
    key: 'F',
    meta: {
      title: '参数管理',
      icon: 'course',
      roles: ['admin', 'editor']
    },
    children: [
    ]
  },

  {
    path: '/dropdown',
    component: Layout,
    redirect: '/dropdown/list',
    name: 'Dropdown',
    key: 'J',
    meta: {
      title: '自定义参数管理',
      icon: 'course',
      roles: ['admin', 'editor']
    },
    children: [
    ]
  },

  {
    path: '',
    component: Layout,
    redirect: 'dashboard',
    key: 'M',
    hidden: true,
    meta: {
      title: '班组管理',
      icon: 'course',
      roles: ['admin', 'editor']
    },
    children: [
    ]
  },

  {
    path: '',
    component: Layout,
    redirect: 'dashboard',
    key: 'N',
    hidden: true,
    meta: {
      title: '数据录入管理',
      icon: 'course',
    },
    children: [
    ]
  },

  { path: '*', redirect: '/404', hidden: true }
]

const asyncChildrenRoutes=[
    {
      path: 'dashboard',
      component: 'views/dashboard/index',
      name: 'Dashboard',
      key: 'A1',
      meta: { title: '首页', icon: 'dashboard', affix: true }
    },
    {
      path: 'role',
      component: 'views/permission/role',
      name: 'RolePermission',
      key: 'B1',
      meta: {
        title: '权限管理',
        roles: ['admin']
      }
    },
      {
        path: 'create',
        key:'G1',
        component: '/views/usrgroup/create',
        name: 'CreateUsrgroup',
        meta: { title: '用户组新增', icon: 'edit' }
      },
      {
        path: 'edit/:id(\\d+)',
        key:'G2',
        component: '/views/usrgroup/edit',
        name: 'EditUsrgroup',
        meta: { title: '用户组编辑', noCache: true, activeMenu: '/usrgroup/list' },
        hidden: true
      },
      {
        path: 'list',
        key:'G3',
        component: '/views/usrgroup/list',
        name: 'UsrgroupList',
        meta: { title: '用户组清单', icon: 'list' }
      },
      {
        path: 'create',
        key:'H1',
        component: '/views/boudf/create',
        name: 'CreateBOUDF',
        meta: { title: 'LOT数据新增', icon: 'edit' },
        hidden: true
      },
      {
        path: 'edit/:id(\\d+)',
        key:'H2',
        component: '/views/boudf/edit',
        name: 'EditBOUDF',
        meta: { title: 'LOT数据更新', noCache: true, activeMenu: '/boudf/list' },
        hidden: true
      },
      {
        path: 'list',
        key:'H3',
        component: '/views/boudf/list',
        name: 'BOUDFList',
        meta: { title: 'LOT数据履历', icon: 'list' }
      },
      {
        path: 'create',
        key:'I1',
        component: () => import('@/views/mpcpend/create'),
        name: 'CreateMPCP',
        meta: { title: '生产/质量数据新增', icon: 'edit' },
        hidden: true
      },
      {
        path: 'edit/:id(\\d+)',
        key:'I2',
        component: () => import('@/views/mpcpend/edit'),
        name: 'EditMPCP',
        meta: { title: '生产/质量数据更新', noCache: true, activeMenu: '/mpcpend/list' },
        hidden: true
      },
      {
        path: 'list',
        key:'I3',
        component: () => import('@/views/mpcpend/list'),
        name: 'MPCPList',
        meta: { title: '生产/质量数据清单', icon: 'list' }
      },
      {
        path: 'create',
        component: 'views/usr/create',
        key: 'C1',
        name: 'CreateUsr',
        meta: { title: '用户新增', roles: ['admin'] }
      },
      {
        path: 'edit/:id(\\d+)',
        component: 'views/usr/edit',
        key: 'C2',
        name: 'EditUsr',
        meta: { title: '用户编辑', noCache: true },
        hidden: true
      },
      {
        path: 'list',
        component: 'views/usr/list',
        key: 'C3',
        name: 'UsrList',
        meta: { title: '用户清单', icon: 'list' }
      },
      {
        path: 'create',
        component: 'views/mpcp/create',
        key: 'D1',
        name: 'CreateMPCP',
        meta: { title: 'LOT执行新增', icon: 'edit' }
      },
      {
        path: 'edit/:id(\\d+)',
        component: 'views/mpcp/edit',
        key: 'D2',
        name: 'EditMPCP',
        meta: { title: 'LOT执行更新', noCache: true },
        hidden: true
      },
      {
        path: 'list',
        component: 'views/mpcp/list',
        key: 'D3',
        name: 'MPCPList',
        meta: { title: 'LOT执行履历', icon: 'list' }
      },
      {
        path: 'create',
        component: 'views/res/create',
        key: 'E1',
        name: 'CreateRes',
        meta: { title: '设备新增', icon: 'edit', roles: ['admin'] }
      },
      {
        path: 'edit/:id(\\d+)',
        component: 'views/res/edit',
        key: 'E2',
        name: 'EditRes',
        meta: { title: '设备编辑', noCache: true },
        hidden: true
      },
      {
        path: 'list',
        component: 'views/res/list',
        key: 'E3',
        name: 'ResList',
        meta: { title: '设备清单', icon: 'list' }
      },{
        path: 'create',
        component: 'views/edc/create',
        key: 'F1',
        name: 'CreateEDC',
        meta: { title: '参数新增', icon: 'edit', roles: ['admin'] }
      },
      {
        path: 'edit/:id(\\d+)',
        component: 'views/edc/edit',
        key: 'F2',
        name: 'EditEDC',
        meta: { title: '参数编辑', noCache: true },
        hidden: true
      },
      {
        path: 'list',
        component: 'views/edc/list',
        key: 'F3',
        name: 'EDCList',
        meta: { title: '参数管理', icon: 'list' }
      },{
        path: 'create',
        component: 'views/dropdown/create',
        key: 'J1',
        name: 'CreateDropdown',
        meta: { title: '参数新增', icon: 'edit', roles: ['admin'] }
      },
      {
        path: 'edit/:id(\\d+)',
        component: 'views/dropdown/edit',
        key: 'J2',
        name: 'EditDropdown',
        meta: { title: '参数编辑', noCache: true },
        hidden: true
      },
      {
        path: 'list',
        component: 'views/dropdown/list',
        key: 'J3',
        name: 'DropdownList',
        meta: { title: '参数管理', icon: 'list' }
      },
      {
        path: 'index/:hj',
        component: 'views/dashboard/index',
        key: 'M1',
        name: 'dashboard_hj',
        meta: { title: '混胶工程'},
        hidden: true
      },
      {
        path: 'index/:tb',
        component: 'views/dashboard/index',
        key: 'M2',
        name: 'dashboard_tb',
        meta: { title: '涂布工程'},
        hidde: true
      },
      {
        path: 'index/:fq',
        component: 'views/dashboard/index',
        key: 'M3',
        name: 'dashboard_fq',
        meta: { title: '熟化/分切工程'},
        hidden: true
      },
      {
        path: 'index/:hj',
        component: 'views/dashboard/index',
        key: 'N1',
        name: 'dashboard_hj',
        meta: { title: '混胶工程生产数据'},
        hidden: true
      },
      {
        path: 'index/:tb',
        component: 'views/dashboard/index',
        key: 'N2',
        name: 'dashboard_tb',
        meta: { title: '涂布工程生产数据'},
        hidde: true
      },
      {
        path: 'index/:fq',
        component: 'views/dashboard/index',
        key: 'N3',
        name: 'dashboard_fq',
        meta: { title: '熟化/分切工程生产数据'},
        hidden: true
      },
      {
        path: 'index/:fq',
        component: 'views/dashboard/index',
        key: 'N4',
        name: 'dashboard_zl',
        meta: { title: '质量数据'},
        hidden: true
      }
]

export function getCommonRoutes(constantBaseRoutes,asyncBaseRoutes,asyncChildrenRoutes,keys){
  //var _keys = ['A1','B1','C1','C2','C3','D1','D2','D3','E1','E2','E3','F1','F2','F3']
  var _keys = keys
  var _routes = [...constantBaseRoutes]

  var _mainKeys = [...new Set(_keys.map(item=> item.substr(0,1)))];

  _mainKeys.forEach(n=>{
    var _mainRoute = asyncBaseRoutes.filter(v=>v.key == n)[0];

    var _subRoutes = deepClone(asyncChildrenRoutes.filter(v=>v.key.substr(0,1) == n).sort((a,b)=>a.key.substr(1,2)*1-b.key.substr(1,2)*1))

    _mainRoute.children = [..._subRoutes]
    _routes.push(_mainRoute)
  })

  return _routes;
}

export function getUserRoutes(keys){
  //var _keys = ['A1','B1','C1','C2','C3','D1','D2','D3','E1','E2','E3','F1','F2','F3']
  var _keys = keys
  var _routes = [...constantBaseRoutes]

  var _mainKeys = [...new Set(_keys.map(item=> item.substr(0,1)))];

  _mainKeys.forEach(n=>{
    var _mainRoute = asyncBaseRoutes.filter(v=>v.key == n)[0];

    var _dkeys = deepClone(keys.filter(v=>v.substr(0,1) == n));

    var _subRoutes = deepClone(asyncChildrenRoutes.filter(v=>_dkeys.indexOf(v.key)>=0).sort((a,b)=>a.key.substr(1,2)*1-b.key.substr(1,2)*1))

    _mainRoute.children = [..._subRoutes]
    _routes.push(_mainRoute)
  })

  return _routes;
}

export function dateAddDays(num = 1,date = false) {
　　if (!date) {
　　　　date = new Date();//没有传入值时,默认是当前日期
　　　　date = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
　　}
　　date += " 00:00:00";//设置为当天凌晨12点
　　date = Date.parse(new Date(date))/1000;//转换为时间戳
　　date += (86400) * num;//修改后的时间戳
　　var newDate = new Date(parseInt(date) * 1000);//转换为时间
　　return newDate.getFullYear() + '-' + (newDate.getMonth() + 1).toString().padStart(2,'0') + '-' + newDate.getDate().toString().padStart(2,'0') ;
}

export function parseDate(time) {
  return parseTime(time, '{y}-{m}-{d}')
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xDC00 && code <= 0xDFFF) i--
  }
  return s
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

export function limitInputNumber(value, name, decim=0) {
    // ("" + value) // 第一步：转成字符串
    //   .replace(/[^\d^\.]+/g, "") // 第二步：把不是数字，不是小数点的过滤掉
    //   .replace(/^0+(\d)/, "$1") // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
    //   .replace(/^\./, "0.") // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
    //   .match(/^\d*(\.?\d{0,2})/g)[0] || ""; // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数
  const pattern = new RegExp(`\\d*(\\.?\\d{0,${decim}})`, "g");
  //console.log('limitInput------',value,name,this.list[0][name],pattern)
  return ("" + value).replace(/[^\d^\.]+/g, "").replace(/^0+(\d)/, "$1").replace(/^\./, "0.") .match(pattern)[0] || "";
}

export function unique (arr) {
  return Array.from(new Set(arr))
}